package com.youens.navigationdrawertest.ui.favorite

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.youens.navigationdrawertest.MainActivity
import com.youens.navigationdrawertest.R
import com.youens.navigationdrawertest.database.DataBaseUtils

class FavoriteFragment : Fragment() {

    private lateinit var favoriteViewModel: FavoriteViewModel
    lateinit var databaseUtil: DataBaseUtils
    lateinit var allFavorite:MutableList<Record>
    lateinit var favoriteListView:ListView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        databaseUtil = (activity as MainActivity).getDataBaseUtils()
    }
    override fun onStart() {
        super.onStart()
        favoriteListView = view!!.findViewById(R.id.favorite_records_listView)
        allFavorite = databaseUtil.getAllFavorite()
        var adapter = RecordAdapter(allFavorite,context!!)
        favoriteListView.adapter=adapter
        favoriteListView.setOnItemLongClickListener { parent, view, position, id ->
            var builder = AlertDialog.Builder(context!!)
            builder.setTitle("取消收藏")
            builder.setMessage("是否确认?")
            builder.setPositiveButton("是") {
                    dialog, id ->
                Toast.makeText(activity, "已取消收藏", Toast.LENGTH_SHORT).show()
                var word = allFavorite[position].word
                var id=databaseUtil.getWordsId(word)
                databaseUtil.cancelFavourite(id)
                allFavorite.removeAt(position)
                adapter.notifyDataSetChanged()
            }
            builder.setNegativeButton("否") {
                    dialog, id ->
                Toast.makeText(activity, "未取消收藏", Toast.LENGTH_SHORT).show()
            }
            val dialog: AlertDialog = builder.create()
            dialog.setCancelable(false)
            dialog.show()
            true
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        favoriteViewModel =
            ViewModelProviders.of(this).get(FavoriteViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_favorite, container, false)
        //val textView: TextView = root.findViewById(R.id.text_gallery)
        //favoriteViewModel.text.observe(this, Observer {
        //    textView.text = it
        //})
        return root
    }
}